<?php

namespace App\Http\Controllers;

use App\Http\Requests\EditUserRequest;
use App\Models\BirthdayPrerogativeGetRecord;
use App\Models\ContinueSigninRecord;
use App\Models\Mcard;
use App\Models\MemberOptionalField;
use App\Models\Merchant;
use App\Models\Prerogative;
use App\Models\PrerogativeMcard;
use App\Models\WxcardPrerogative;
use App\Models\WxuserMcard;
use App\Repositories\UserRepository;
use App\Repositories\CardRepository;
use Illuminate\Http\Request;


class UserCenterController extends Controller
{

    /**
     * 会员卡列表
     * @return view
     */
    public function cardList(CardRepository $repository)
    {
        $wxcards = $repository->getWxuserMcards();

        if($wxcards->count('*') == 1){
            $wxuser_mcard = $wxcards->first();

            if(empty($wxuser_mcard)) return abort(404,'未找到该会员卡信息');

            session(['web_wxuser_mcard'=>$wxuser_mcard]);
            session(['web_merchant'=>Merchant::find($wxuser_mcard->id_merchant)]);
            return redirect('user-center');
        }

        return view('user.card_list',compact('wxcards'));
    }

    public function wxcardLogin(Request $request,CardRepository $repository)
    {
        $wxcard_id = $request->id_wxuser_mcard;
        $wxuser_mcard = WxuserMcard::find($wxcard_id);

        if(empty($wxuser_mcard)) return abort(404,'未找到该会员卡信息');

        $auth_has_wxcard_ids = $repository->getCardsByAuthUser()->pluck('id_wxuser_mcard');

        if($auth_has_wxcard_ids->search($wxcard_id) === false) return abort(403,'拒绝访问');

        session(['web_wxuser_mcard'=>$wxuser_mcard]);
        session(['web_merchant'=>Merchant::find($wxuser_mcard->id_merchant)]);

        return redirect('user-center');
    }

    /**
     * 绑定手机号
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function bindPhone(Request $request,CardRepository $repository)
    {
        $secret_param = session('share_secret_param','');

        $id_merchant = $request->route('merchant_id');

        if($id_merchant) {
            $merchant = Merchant::find($id_merchant);

            if($merchant) session(['web_merchant'=>$merchant]);
        }
        return view('user.bind_phone',compact('secret_param'));
    }

    /**
     * 完善会员信息
     * @param Request $request
     * @param CardRepository $repository
     * @return view
     *
     */
    public function bindUserInfo(Request $request,CardRepository $repository)
    {
        $new_fields = session('web_merchant')->memberOptionalFields()->get()->pluck('name')->toArray();

        return view('user.bind_info',compact('new_fields'));
    }
    /**
     * 会员中心
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function index(Mcard $mcard,CardRepository $repository)
    {
        $cards = $mcard->orderBy('level_code','asc')->where('is_del','N')->where('id_merchant',$this->getSeesionWxuseMcard()->id_merchant)->select('id_mcard','name','level_code')->get();

        $mycard = $this->getSeesionWxuseMcard(true);

//        if(strlen($mycard->remain_credits)>4) $mycard->remain_credits = substr($mycard->remain_credits,0,4).'+';

        $mycard->progress=$this->getProgressByLevel($mycard->id_mcard_level);

        $mycard_prerogative = $repository->getCardPrerogative();

        return view('user.center',compact('cards','mycard_prerogative','mycard'));
    }

    /**
     * @param $level
     * @return string
     * '1002'=>'普卡',
    '1008'=>'银卡',
    '1001'=>'金卡',
     */
    public function getProgressByLevel($level)
    {
        switch ($level){
            case 1:
                return '25%';
                break;
            case 2:
                return '67%';
                break;
            case 3:
                return '100%';
                break;
            default:
                return '25%';
                break;

        }
    }

    /**
     * 积分记录
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function credits()
    {
        $credits_records = $this->getSeesionWxuseMcard()->creditsRecords()->orderBy('created_at','desc')->paginate(10);

        $mycard = $this->getSeesionWxuseMcard();

        $data = $credits_records->groupBy(function($item){
            return $item->created_at->year.'年'.$item->created_at->month.'月';
        });

        return view('user.credits',compact('data','mycard'));
    }

    /**
     * 电子钱包
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function wallet()
    {
        $mycard = $this->getSeesionWxuseMcard();

        $balance_records = $mycard->balanceRecords()->orderBy('created_at','desc')->paginate(10);

        $data = $balance_records->groupBy(function($item){
            return $item->created_at->year.'年'.$item->created_at->month.'月';
        });

        return view('user.wallet',compact('mycard','data'));
    }

    /**
     * 余额明细
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function balanceRecord()
    {
        $mycard = $this->getSeesionWxuseMcard();

        $balance_records = $mycard->balanceRecords()->orderBy('created_at','desc')->paginate(10);

        $data = $balance_records->groupBy(function($item){
            return $item->created_at->year.'年'.$item->created_at->month.'月';
        });

        return view('user.balance_record',compact('mycard','data'));
    }

    /**
     * 打卡
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function punchClock(UserRepository $repository)
    {
        //打卡规则
        $rule = $repository->getFirstSigninShare();
        if(!$rule) return abort(403,'管理员未设置打卡规则，请稍后再来');
        //签到获取的总积分
        $sum_credits = $repository->getCreditsByClock();
        //最近一次签到记录
        $pre_recode = $repository->getRecentlyClockRecord();

        //今天是否签到
        $is_tody_clock = $repository->isPunchClock();

        if($pre_recode  && ($is_tody_clock || $pre_recode->created_at->isYesterday())){
            $residue = $rule->sign_many - $pre_recode->times;
        }else{
            $residue = $rule->sign_many;
        }
        /*$get_button = [
            'text'=>'领取',
            'status'=>0,
        ];

        if(isset($pre_recode) && $residue==0 && $is_tody_clock){
            if(ContinueSigninRecord::where('id_signin_share_record',$pre_recode->id)->first()){
                $get_button['text'] = '已领取';
            }else{
                $get_button['status'] = 1;
            }
        }*/

        return view('user.punch_clock',compact('is_tody_clock','sum_credits','pre_recode','rule','residue'));
    }

    public function powerExplain()
    {
        return view('user.power_explain');
    }

    /**
     * 权益
     * @param $id_wxcard_prerogative
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function powerDetail($id_wxcard_prerogative,CardRepository $repository)
    {
        $prerogative = WxcardPrerogative::find($id_wxcard_prerogative);

        if(!$prerogative) return abort(403,'未找到权益信息');

        $prerogative_type = Prerogative::find($prerogative->id_prerogative);
        $my_card = $this->getSeesionWxuseMcard();

        $has_p = $repository->getCardPrerogative()->pluck('id_wxcard_prerogative')->toArray();

        if(empty($prerogative) || !in_array($id_wxcard_prerogative,$has_p) ) abort(403,'无权查看');

        //权益对象
        $to_member = '所有会员';
        if($prerogative->for_all_member != 'Y'){
            $pr_mcard = PrerogativeMcard::where('id_wxcard_prerogative',$prerogative->id_wxcard_prerogative)->pluck('id_mcard');
            $card_names = Mcard::whereIn('id_mcard',$pr_mcard)->pluck('name');

            if(!empty($card_names->toArray())){
                $to_member = implode(',',$card_names->toArray()).'会员';
            }
        }


        $birthday_gift='';

        if($prerogative->id_prerogative==2) $birthday_gift = $this->getBirthdayGift();

        return view('user.card_power_datail',compact('prerogative','my_card','prerogative_type','birthday_gift','to_member'));
    }

    protected function getBirthdayGift()
    {
        $birthday_gift=['status'=>0, 'text'=>'领取', 'link'=>'#'];

        $record = BirthdayPrerogativeGetRecord::where('id_wxuser_mcard',$this->getSeesionWxuseMcard()->id_wxuser_mcard)
            ->orderBy('created_at','desc')
            ->first();

        if(empty($record) || $record->created_at->year != now()->year){
            if($this->getSeesionWxuseMcard()->member_optional_birthday){

                if(substr(now()->toDateString(),5) == substr($this->getSeesionWxuseMcard()->member_optional_birthday,5)){
                    $birthday_gift['status']='1';
                    $birthday_gift['text']='领取';
                    $birthday_gift['link']='/ajax/birthday-gift/get';
                }

            }else{
                $birthday_gift['status']='2';
                $birthday_gift['text']='去完善生日';
                $birthday_gift['link']='/user/edit';
            }
        }else{
            $birthday_gift['status']='0';
            $birthday_gift['text']='已领取';
            $birthday_gift['link']='#';
        }

        return $birthday_gift;

    }

    /**
     * 修改会员信息
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function edit()
    {
        $new_fileds = session('web_merchant')->memberOptionalFields()->get()->pluck('name')->toArray();

        $wxuser_mcard = $this->getSeesionWxuseMcard();

        return view('user.user_edit',compact('wxuser_mcard','new_fileds'));
    }

    /**
     * 执行修改
     * @param EditUserRequest $request
     * @param UserRepository $userRepository
     * @return \Illuminate\Http\RedirectResponse
     */
    public function update(EditUserRequest $request,UserRepository $userRepository)
    {
        $input_data = $request->except(['_token','_method']);

        if(!isset($input_data['member_optional_gender']) || $input_data['member_optional_gender']==null) $input_data['member_optional_gender']='';
        if(!isset($input_data['member_optional_marriage']) || $input_data['member_optional_marriage']==null) $input_data['member_optional_marriage']='';
        if(!isset($input_data['member_optional_child_sex']) || $input_data['member_optional_child_sex']==null) $input_data['member_optional_child_sex']='';

        $res = $userRepository->updateUserInfo($input_data);

        if($res) return redirect()->route('ucenter')->with('status','修改成功');

        return back()->with('status','修改失败');
    }

    /**
     * 我的消费券
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function myTicktes()
    {
        $my_tickets = $this->getSeesionWxuseMcard()->wxcardTickets()->with('merchantTicket')->get();

        $datas = $my_tickets->each(function($item){
            if($item->status==1 && $item->proof_expiry_time < now()->toDateTimeString()){
                $item->status = 3;
                $item->overdued_at = now()->toDateTimeString();
                $item->save();

                if($item->table_type=='credits_exchange_record'){
                    \DB::table('credits_exchange_record')->where('id',$item->table_id)->update(['status'=>3]);
                }
            }
        })->groupBy(function($ticket){
            return $ticket->status;
        })->toArray();

        return view('user.my_ticktes',compact('datas'));
    }

}
